package com.ponhu.ea2.goodsCenter.bms.api.config;

import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.goodsCenter.bms.api.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.stream.Collectors;

import static com.ponhu.ea2.enums.ResponseCodeEnum.PARAMETER_IS_INCORRECT_800001;

@Slf4j
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {

    //校验框架异常处理
    @ExceptionHandler(BindException.class)
    public ResponseBean validatedBindException(BindException e) {
        String traceId = CommonUtils.getTraceId();
        String servletPath = null;
        try {
            ServletRequestAttributes servletRequestAttributes =
                    (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            servletPath = servletRequestAttributes.getRequest().getServletPath();
        } catch (Exception exception) {
            //nothing to to
        }

        String msg = e.getAllErrors().stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.joining("；"));
        log.error("{} ===>> [{}] ===>> 参数校验异常：[msg={}]", servletPath, traceId, msg);
        return ResponseBean.error(PARAMETER_IS_INCORRECT_800001.getCode(), msg);
    }
}
